package com.cognitran.cssvalidator.ant.output.formatters;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import org.apache.tools.ant.BuildException;
import org.w3c.css.css.StyleReport;
import org.w3c.css.css.StyleReportFactory;

import com.cognitran.cssvalidator.validation.model.CSSValidationResults;

/**
 * A formatter that outputs W3C styled text.
 * 
 * @author garethf
 */
public class W3CStyledTextFormatter extends AbstractOutputFormatter
{

	/** The writer that output is written to. */
	private PrintWriter writer = null;
	
	
	/**
	 * {@inheritDoc}
	 */
	public void init()
	{
		try
		{
			final File output = new File(getOutputLocation(), "/reportw3c.txt");
			writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(output), "utf8"));
		} 
		catch (IOException e) 
		{
			System.err.println(e.getMessage());
			e.printStackTrace();
			// Hmmm, not much to do for now ....
			throw new BuildException("IO problem whilst writing formatted output, error was -> " + e.getMessage(), e);
		}
	}
	
	
	/**
	 * {@inheritDoc}
	 */
	public void cleanup()
	{
		writer.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */
	public void writeFormattedOutput(final File source, final CSSValidationResults results) 
	{
		final String title = source.toString();
        final StyleReport style = StyleReportFactory.getStyleReport(results.getContext(), title,
                                                             results.getCss(), 
                                                             source.getAbsolutePath(), 
                                                             Integer.valueOf(results.getWarningThresholdLevel()));
	        
    	style.print(writer);
	}

}
